package com.storm.auth.behavior

import cn.hutool.core.util.IdUtil
import cn.hutool.core.util.RandomUtil
import com.storm.auth.behavior.factory.UserEntityFactory
import com.storm.auth.mapper.UserMapper
import com.storm.auth.model.table.User
import com.storm.common.enums.UserEnabledEnum
import com.storm.common.exception.StormException
import com.storm.util.md5
import org.springframework.stereotype.Component
import java.time.LocalDateTime

/**
 * 用户相关操作
 */
@Component
class UserBehavior(
    private val userMapper: UserMapper,
    private val userEntityFactory: UserEntityFactory,
) {
    private val saltLength = 6
    private val nicknameLength = 6

    /**
     * 用户注册最后一步，操作入库
     */
    fun addUser(username: String, phone: String, password: String) {

        val now = LocalDateTime.now()

        // 判断用户名是否已存在
        checkUsername(username)
        // 判断手机号是否已存在
        checkPhone(phone)
        val userId = IdUtil.objectId()
        val nickname = RandomUtil.randomString(nicknameLength)
        //存入用户表
        val salt = RandomUtil.randomStringUpper(saltLength)
        //存入用户权限表
        userMapper.insert(
            User(
                userId = userId,
                phone = phone,
                username = username,
                password = password.md5(salt),
                salt = salt,
                createTime = now,
                updateTime = now,
                nickname = nickname,
                enabled = UserEnabledEnum.ENABLED.code
            )
        )
    }

    /**
     * 检查手机号是否存在
     */
    private fun checkPhone(phone: String) {
        if (userEntityFactory.getUserEntityByPhone(phone)
                .isPresent()
        ) {
            throw StormException("手机号已存在")
        }
    }

    /**
     * 检查用户名是否存在
     */
    private fun checkUsername(username: String) {
        if (userEntityFactory.getUserEntityByUsername(username)
                .isPresent()
        ) {
            throw StormException("用户名已存在")
        }
    }


}
